package com.khd.problems_0001_0100;

/**
 * 70. 爬楼梯
 * https://leetcode.cn/problems/climbing-stairs/
 *
 * @author kehandi
 * @title: Problem_0070_ClimbingStairs
 * @projectName algorithm
 * @date 2022/9/17 11:09
 */
public class Problem_0070_ClimbingStairs {

    /**
     * 解法1：递归算法
     * 时间复杂度O(2^N)
     *
     * @param n
     * @return
     */
    public static int climbStairs1(int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }

        return climbStairs1(n - 1) + climbStairs1(n - 2);
    }

    /**
     * 解法2：记忆化递归
     *
     * @param n
     * @return
     */
    public static int climbStairs2(int n) {
        int[] memo = new int[n + 1];
        return climbStairsMemo(n, memo);
    }

    private static int climbStairsMemo(int n, int[] memo) {
        if (memo[n] > 0) {
            return memo[n];
        }

        if (n == 1) {
            memo[n] = 1;
        } else if (n == 2) {
            memo[n] = 2;
        } else {
            memo[n] = climbStairsMemo(n - 1, memo) + climbStairsMemo(n - 2, memo);
        }
        return memo[n];
    }

    /**
     * 解法3：动态规划
     * 时间复杂度O(N)
     *
     * @param n
     * @return
     */
    public static int climbStairs3(int n) {
        if (n == 1) {
            return 1;
        }

        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    /**
     * 解法3：动态规划（滚动数组）
     * 时间复杂度O(N)
     *
     * @param n
     * @return
     */
    public static int climbStairs4(int n) {
        int p = 0, q = 0, r = 1;
        for (int i = 0; i < n; i++) {
            p = q;
            q = r;
            r = p + q;
        }
        return r;
    }

    public static void main(String[] args) {
        System.out.println(climbStairs3(44));
    }
}
